<script setup>
    import {ref} from 'vue'
    import {Edit, Delete} from '@element-plus/icons-vue'
    import {useUserInfoStore} from '@/store/user.js'
    import {userInfoEditService} from "@/api/user";

    const userInfoStore = useUserInfoStore();
    let token = localStorage.getItem('token');
    //获取商品列表数据
    import {
        categoryListService,
        goodDeleteService,
        goodListService,
        goodsAddService,
        goodUpdateService
    } from "@/api/good";
    //分页条数据模型
    const pageNum = ref(1)
    const total = ref(1)
    const pageSize = ref(3)
    //每页条数变化时调用
    const onSizeChange = (size) => {
        pageSize.value = size
        goodList()
    }
    //页码变化时调用此函数
    const onCurrentChange = (num) => {
        pageNum.value = num
        goodList()
    }
    //用于搜索
    const gName = ref(null)
    const categories = ref([
        {
            "gcId": 1,
            "gcName": "女装"
        },
        {
            "gcId": 2,
            "gcName": "食品",
        }
    ])

    //商品分类列表
    const categoryList = async () => {
        let result = await categoryListService();
        console.log('商品分类列表：')
        console.log(result.data)
        if (result.data != null) {
            categories.value = result.data.map(item => ({
                gcId: item.gcId,
                gcName: item.gcName,
            }))
        } else {
            ElMessage.error("出现问题")
        }
    }

    const goods = ref([
        // {
            // "gid": 1,
            // "gname": "连衣裙",
            // "gcId": 1,
            // "gcName": "女装",
            // "gimg": "https://stzk.oss-cn-beijing.aliyuncs.com/a82a6188-d9bb-47d0-b1c1-4519512d05d4.png",
            // "gunitprice": "80",
            // "gdetails": "这是一款适合夏天的连衣裙",
            // "gstate": "审核不通过",
            // "g_reason": "商品详情与图片不符"
        // }
    ])
    const goodList = async () => {
        let params = {
            pageNum: pageNum.value,
            pageSize: pageSize.value,
            gName: gName.value ? gName.value : null,
        }
        let result = await goodListService(params);
        if (result.data != null) {
            total.value = result.data.total;
            goods.value = result.data.items;
            for (let i = 0; i < goods.value.length; i++) {
                let good = goods.value[i];
                for (let j = 0; j < categories.value.length; j++) {
                    if (good.gcId === categories.value[j].gcId) {
                        good.gcName = categories.value[j].gcName;
                    }
                }
            }
        } else {
            ElMessage("没有搜索到商品")
        }
    }

    categoryList()
    goodList();

    const goodModel = ref({
        gid: '',
        gname: '',
        gcId: '',
        gimg: '',
        gunitprice: '',
        gdetails: '',
        gstate: ''
    })
    const visibleDrawer = ref(false)
    const selectedRowIndex=ref(null);
    // 添加表单
    const addGoods = async () => {
        //验证商品价格
        if (!validateInput()) {
            ElMessage.error('请输入正确的金额数,只能输入两位小数！')
            return;
        }
        let result = await goodsAddService(goodModel.value);
        ElMessage.success(result.msg ? result.msg : "添加成功")
        //让抽屉消失
        visibleDrawer.value = false;
        goodList()
        cancelsubmit()
    }
    //编辑表单
    const visibleDialog = ref(false)
    const showDialog = (row) => {
        visibleDialog.value = true;
        selectedRowIndex.value=goods.value.indexOf(row)+1;
        goodModel.value.gid = row.gid;
        goodModel.value.gname = row.gname;
        goodModel.value.gcId = row.gcId;
        goodModel.value.gcName = row.gcName;
        goodModel.value.gimg = row.gimg;
        goodModel.value.gunitprice = row.gunitprice;
        goodModel.value.gdetails = row.gdetails;
        goodModel.value.gstate = row.gstate;
    }
    const updateGoods = async() => {
        //验证商品价格
        if (!validateInput()) {
            ElMessage.error('请输入正确的金额数,只能输入两位小数！')
            return;
        }
        let result=await goodUpdateService(goodModel.value);
        console.log(result)
        ElMessage.success(result.msg ? result.msg : "修改成功")
        goodList()
        //隐藏弹窗
        visibleDialog.value = false;
    }
    import {ElMessage, ElMessageBox} from 'element-plus'
    //删除
    const deleteGoods = (row) => {
        //提示用户  确认框
        ElMessageBox.confirm(
            '你确认要删除该知识点信息吗?',
            '温馨提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async()=>{
            let result=await goodDeleteService(row.gid);
            console.log('gid为：')
            console.log(row.gid)
            if(result.code===0){
                ElMessage.success("删除成功")
            }else{
                ElMessage.error("删除失败")
            }
            goodList()
        })
    }
    //清空模型
    const clearData = () => {
        goodModel.value.gname = '';
        goodModel.value.gcName = '';
        goodModel.value.gcId = '';
        goodModel.value.gimg = '';
        goodModel.value.gunitprice = '';
        goodModel.value.gdetails = '';
        goodModel.value.gstate = '';
    }

    //取消添加
    const cancelsubmit = () => {
        goodModel.value.gname = '';
        goodModel.value.gcName = '';
        goodModel.value.gcId = 1;
        goodModel.value.gimg = '';
        goodModel.value.gunitprice = '';
        goodModel.value.gdetails = '';
        goodModel.value.gstate = '';
        visibleDrawer.value = false;
        visibleDialog.value = false;
    }


    //上传头像成功回调
    const handleAvatarSuccess = (img) => {
        //img就是后台响应的数据，格式为：{code:状态码，message：提示信息，data: 图片的存储地址}
        goodModel.value.gimg = img.data
    }
    //上传头像验证
    const beforeAvatarUpload = (rawFile) => {
        const allowedTypes = ['image/jpeg', 'image/png'];
        if (!allowedTypes.includes(rawFile.type)) {
            ElMessage.error('头像必须是 JPG 或 PNG 格式！');
            return false;
        } else if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('头像大小不能超过5MB！');
            return false;
        }
        return true;
    };


    //表单校验规则
    const validateInput = () => {
        if (!goodModel.value.gunitprice) {
            return false;
        }
        const numericRegex = /^[0-9]+(\.[0-9]{1,2})?$/;//只能输入两位小数
        if (!numericRegex.test(goodModel.value.gunitprice)) {
            return false;
        }
        // 金额是否大于0
        return parseFloat(goodModel.value.gunitprice) > 0;
    }
    //表单校验规则
    const rules = {
        gname: [{
            required: true, message: "请输入商品名称", trigger: 'blur'
        }],
        gunitprice: [{
            required: true, message: "请输入商品单价", trigger: 'blur'
        }, {
            validator: (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入商品单价'));
                } else if (!/^[0-9]+(\.[0-9]{1,2})?$/.test(value)) {
                    callback(new Error('请输入正确的价格格式（最多两位小数）'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }],
    }

    // 将商品状态转换为对应文字
    const getStatusLabel = (gstate) => {
        switch (gstate) {
            case 0:
                return '未审核';
            case 1:
                return '审核已通过';
            case 2:
                return '审核未通过';
            default:
                return '';
        }
    }
    //重置按钮
    const resetSearch=()=>{
        gName.value=null;
        pageNum.value=1;
        pageSize.value=3;
        goodList();
    }
</script>
<template>
    <el-card class="cat-container">
        <div class="header">
            <el-form inline>
                <el-form-item>
                    <el-input placeholder="请输入商品名" v-model="gName" class="search-input"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="search-btn" @click="goodList()">查询</el-button>
                    <el-button type="primary" class="reset-btn" @click="resetSearch()">重置</el-button>
                </el-form-item>
            </el-form>
            <el-button type="primary" class="add-btn" @click="visibleDrawer=true; clearData()">
                <el-icon>
                    <Plus/>
                </el-icon>
                添加商品
            </el-button>
        </div>
        <el-card class="table-all">
            <el-row>
                <el-table :data="goods" class="userList-table"
                          :header-cell-style="{ textAlign: 'center' ,height: '70px', background: 'ghostwhite'} "
                          :cell-style="{ textAlign: 'center' }">
                    <el-table-column type="expand">
                        <template v-slot="{ row }">
                            <div>
                                <p style="margin-left: 60px"><strong>商品详情:</strong> {{ row.gdetails }}</p>
                                <p style="margin-left: 60px" v-if="row.greason">
                                    <strong>审核不通过理由：</strong>{{ row.greason }}</p>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="序号" width="90">
                        <template v-slot="scope">
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="商品名称" prop="gname" class="s-good-name" width="220"></el-table-column>
                    <el-table-column label="商品分类" prop="gcName" width="120"></el-table-column>
                    <el-table-column label="商品图片" prop="gimg" width="120">
                        <template #default="scope">
                            <el-image :src="scope.row.gimg" v-if="scope.row.gimg"
                                      style="width: 90px; height: 90px;"></el-image>
                            <el-image :src="require('@/assets/空2.png')" v-else
                                      style="width: 100px; height: 90px;"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品单价" prop="gunitprice" width="120"></el-table-column>
                    <el-table-column label="商品状态" prop="gstate" width="140">
                        <template v-slot="scope">
                            {{ getStatusLabel(scope.row.gstate) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="130">
                        <template #default="scope">
                            <el-button :icon="Edit" circle plain type="primary" size="small"
                                       style="width: 32px; height: 32px"
                                       @click="showDialog(scope.row)"></el-button>
                            <el-button :icon="Delete" circle plain type="danger" size="small"
                                       style="width: 32px; height: 32px"
                                       @click="deleteGoods(scope.row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
            <template #empty>
                <el-empty description="没有数据"/>
            </template>
        </el-card>

        <!--                分页条-->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3,5,10,15]"
                       layout="jumper,total,sizes,prev,paper,next" background :total="total"
                       @size-change="onSizeChange" @current-change="onCurrentChange"
                       style="margin-top: 20px;justify-content: flex-end"/>
        <!--        添加商品弹窗-->
        <el-drawer v-model="visibleDrawer" direction="rtl" size="50%"
                   style="height: 600px">
            <template #header="添加商品">
                <h4 style="font-size: 20px;">添加商品</h4>
            </template>
            <el-form :model="goodModel" label-width="150px" class="chouti" :rules="rules">
                <el-form-item label="商品名称">
                    <el-input v-model="goodModel.gname" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品类别">
                    <el-select placeholder="请选择" v-model="goodModel.gcId" style="width: 85%;">
                        <el-option v-for="t in categories" :key="t.gcId" :label="t.gcName" :value="t.gcId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品图片">
                    <div class="avatar">
                        <el-upload
                                class="avatar-uploader"
                                action="/api/user/uploadAvatar"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :auto-upload="true"
                                name="file"
                                :headers="{'Authorization':token}"
                                :before-upload="beforeAvatarUpload"
                        >
                            <el-image :src="goodModel.gimg" v-if="goodModel.gimg"/>
                            <el-icon class="avatar-uploader-icon" v-else>
                                <Plus/>
                            </el-icon>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="商品单价">
                    <el-input v-model="goodModel.gunitprice" placeholder="请输入商品单价（元）"
                              @input="formatPrice"></el-input>
                </el-form-item>
                <el-form-item label="商品详情">
                    <el-input v-model="goodModel.gdetails" placeholder="请输入商品详情"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addGoods()">确定</el-button>
                    <el-button type="info" @click="cancelsubmit">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
        <!--        编辑框-->
        <el-drawer v-model="visibleDialog" direction="rtl" size="50%"
                   style="height: 600px;">
            <template #header="编辑商品">
                <h4 style="font-size: 20px;">编辑商品</h4>
            </template>
            <!-- 编辑商品表单 -->
            <el-form :model="goodModel" label-width="150px" class="chouti" :rules="rules">
                <template #header="编辑商品">
                    <h4 style="font-size: 20px;">编辑商品</h4>
                </template>
                <el-form-item style="display: none">
                    <el-input v-model="goodModel.gid" readonly></el-input>
                </el-form-item>
                <el-form-item label="商品编号" style="font-size: 10px !important">
                    <el-input v-model="selectedRowIndex"></el-input>
                </el-form-item>
                <el-form-item label="商品名称">
                    <el-input v-model="goodModel.gname" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品类别">
                    <el-select placeholder="请选择" v-model="goodModel.gcId" style="width: 85%;">
                        <el-option v-for="t in categories" :key="t.gcId" :label="t.gcName" :value="t.gcId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品图片">
                    <div class="avatar">
                        <el-upload
                                class="avatar-uploader"
                                action="/api/user/uploadAvatar"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :auto-upload="true"
                                name="file"
                                :headers="{'Authorization':token}"
                                :before-upload="beforeAvatarUpload"
                        >
                            <el-image title="单击上传新商品图片"
                                      :src="goodModel.gimg ? goodModel.gimg : require('@/assets/空2.png')"
                                      class="avatar"/>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="商品单价">
                    <el-input v-model="goodModel.gunitprice" placeholder="请输入商品单价"></el-input>
                </el-form-item>
                <el-form-item label="商品详情">
                    <el-input v-model="goodModel.gdetails" placeholder="请输入商品详情"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="updateGoods()">确定</el-button>
                    <el-button type="info" @click="cancelsubmit">取消</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>

<script>
    import {Plus} from "@element-plus/icons-vue";

    export default {
        name: "GoodsManagement",
        components: {Plus},
        data() {
            return {
                isHovered: false
            };
        },
        computed: {
            avatarStyle() {
                return {
                    transform: this.isHovered ? 'scale(1.2)' : 'scale(1)',
                    transition: 'all 0.3s ease'
                };
            }
        }
    }
</script>


<style scoped>
    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 30px;
        background-color: #ffffff;
        margin-top: -10px;
        margin-left: -10px;
        margin-right: -15px;
        padding-left: 5px;
        padding-right: 5px;
    }

    .add-btn {
        height: 20px;
        font-size: 10px;
        background-color: rgba(255, 230, 246, 0.68);
        color: #f13b82;
        border-color: #f13b82;
    }

    .cat-container {
        min-height: 100vh;
        background-color: rgba(135, 206, 250, 0.2);
        width: 100%;
        height: 100vh;
        font-size: 10px;
        /*overflow-y: scroll;*/
    }

    .table-all {
        background-color: rgba(255, 200, 234, 0.68);
        margin: 5px -10px 10px -5px;
        border-radius: 10px;
        height: 70vh;
        overflow-y: scroll;
    }

    .userList-table {
        /*width: 100%;*/
        margin-left: -5px;
        /*margin-right: -10px;*/
        font-size: 10px;
    }

    ::v-deep .el-form-item__label {
        font-size: 12px;
    }

    ::v-deep .el-select__wrapper {
        font-size: 10px;
    }

    /* 使用深度选择器来选中并覆盖下拉菜单的样式 */
    /*::v-deep .el-select-dropdown .el-select-dropdown__wrap {*/
    /*    max-height: 50px; !* 设置你想要的最大高度 *!*/
    /*    overflow-y: auto; !* 启用垂直滚动条 *!*/
    /*}*/
    ::v-deep .el-option {
        max-height: 50px;
        overflow-y: auto;
    }

    .chouti .el-input {
        height: 30px;
        font-size: 10px;
        width: 200px;
    }

    .chouti .el-option {
        font-size: 10px;
    }

    .avatar {
        margin-left: 10px;
        width: 80px;
        height: 80px;
        display: block;
    }
    .s-good-name{
        overflow: hidden; /*多出的部分隐藏*/
        text-overflow: ellipsis;
        white-space: nowrap; /*防止换行*/
    }

    .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
        border-color: var(--el-color-primary);
    }
    .avatar-uploader{
        width: 70px;
        height: 70px;
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 70px;
        height: 70px;
        text-align: center;
    }

    .search-input {
        font-size: 10px;
        height: 25px;
        margin-top: 20px;
        background-color: #f13b82;
    }

    .search-btn {
        height: 25px;
        margin-left: 30px;
        background-color: lavender;
        color: mediumpurple;
        border-color: mediumpurple;
        margin-right: 30px;
        margin-top: 20px;
        margin-bottom: 0;
        font-size: 10px;
    }

    .search-btn:hover {
        background-color: mediumpurple;
        color: white;
    }

    .reset-btn {
        height: 25px;
        margin-left: 30px;
        margin-right: 50px;
        margin-bottom: 0;
        margin-top: 20px;
        font-size: 10px;
        background-color: beige;
        color: darkorange;
        border-color: darkorange;
    }

    .reset-btn:hover {
        background-color: darkorange;
        color: white;
    }

    /*商品详情太长隐藏*/
    .detailHide {
        text-overflow: ellipsis; /* 一行显示*/
        white-space: nowrap; /* 不换行 */
        width: 50px;
        overflow: hidden;
    }

    .el-pagination {
        margin-top: 0px;
        font-size: 10px;
        height: 20px !important;
        justify-content: flex-end;
    }
</style>
